﻿using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Common;
using DFGK_WMS.Common.HttpModule;
using DFGK_WMS.Common.WebSocketModule;
using DFGK_WMS.Model.Dto;
using DFGK_WMS.Model.Wcs;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace DFGK_WMS.WebAPI.Controllers.PC.设备管理
{
    /// <summary>
    /// 设备管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "PC")]
    public class WCSController : BaseController
    {
        private readonly IReceivingOrderDetailService receivingOrderDetailService;
        private readonly IShippingOrderDetailService shippingOrderDetailService;
        private readonly ITransferBinOrderService transferBinOrderService;
        private readonly ICellService cellService;
        private readonly ICtmHttpClient httpClient;
        private readonly IPalletRepository palletRepository;
        private readonly WcsHttpClient wcsHttp;
        private readonly WebSocketConnectManager wsManager;
        private readonly IPutawayOrderRepository putawayOrderRepository;
        private readonly IPickingOrderRepository pickingOrderRepository;

       /// <summary>
       /// /
       /// </summary>
       /// <param name="environment"></param>
       /// <param name="receivingOrderDetailService"></param>
       /// <param name="shippingOrderDetailService"></param>
       /// <param name="transferBinOrderService"></param>
       /// <param name="putawayOrderRepository"></param>
       /// <param name="pickingOrderRepository"></param>
       /// <param name="cellService"></param>
       /// <param name="httpClient"></param>
       /// <param name="palletRepository"></param>
       /// <param name="wcsHttp"></param>
       /// <param name="wsManager"></param>
        public WCSController(IWebHostEnvironment environment, IReceivingOrderDetailService receivingOrderDetailService, IShippingOrderDetailService shippingOrderDetailService, ITransferBinOrderService transferBinOrderService, IPutawayOrderRepository putawayOrderRepository,IPickingOrderRepository pickingOrderRepository,ICellService cellService,ICtmHttpClient httpClient,IPalletRepository palletRepository,WcsHttpClient wcsHttp, WebSocketConnectManager wsManager) : base(environment)
        {
            this.receivingOrderDetailService = receivingOrderDetailService;
            this.shippingOrderDetailService = shippingOrderDetailService;
            this.transferBinOrderService = transferBinOrderService;
            this.cellService = cellService;
            this.httpClient = httpClient;
            this.palletRepository = palletRepository;
            this.wcsHttp = wcsHttp;
            this.wsManager = wsManager;
            this.putawayOrderRepository = putawayOrderRepository;
            this.pickingOrderRepository = pickingOrderRepository;
        }

        /// <summary>
        /// 任务上报
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult TasklikuAppear(TaskDto m)
        {
            if (string.IsNullOrEmpty(m.taskCode))
            {
                return Ok(BaseResult.Result("400", "参数有误！"));
            }
            string message = "";
            bool result = false;
            string end = m.taskCode.Substring(0, 3);
            if (end == "PUT")
                result = receivingOrderDetailService.FinishReceivingOrderDetail(m.taskCode, out message);
            else if (end == "OUT")
                result = shippingOrderDetailService.FinishShippingOrderDetail(m.taskCode, out message);
            else if(end == "ORT")
                result = shippingOrderDetailService.FinishShippingOutZeroQty(m.taskCode, out message);
            else if (end == "SRT")
                result = shippingOrderDetailService.FinishPickingShippingOrderDetail(m.taskCode, out message);
            else if (end == "TRA")
                result = transferBinOrderService.FinishTransferBinOrder(m.taskCode, out message);
            if (result)
            {
                var putlist = putawayOrderRepository.GetEntityWhereAll(x => x.Status == 4);
                List<PutPickQuestDto> putPickQuestDtoslist = new List<PutPickQuestDto>();
                if (putlist.Any())
                {
                    foreach (var dto in putlist)
                    {
                        PutPickQuestDto putPickQuestDto = new PutPickQuestDto();
                        putPickQuestDto.Code = dto.Code;
                        if (dto.BillType == 1)
                            putPickQuestDto.BillType = "入库";
                        else
                            putPickQuestDto.BillType = "拣选入库";
                        if (dto.SourceType == 3)
                            putPickQuestDto.BillType = "移库";
                        putPickQuestDto.PalletBarcode = dto.PalletBarcode;
                        putPickQuestDto.LocationCode = dto.LocationCode;
                        putPickQuestDto.BatchNo = dto.BatchNo;
                        putPickQuestDto.Qty = dto.Qty;
                        putPickQuestDto.MaterialCode = dto.MaterialCode;
                        putPickQuestDtoslist.Add(putPickQuestDto);
                    }
                }
                var picklist = pickingOrderRepository.GetEntityWhereAll(x => x.Status == 4);
                if (picklist.Any())
                {
                    foreach (var dto in picklist)
                    {
                        PutPickQuestDto putPickQuestDto = new PutPickQuestDto();
                        putPickQuestDto.Code = dto.Code;
                        if (dto.BillType == 1)
                            putPickQuestDto.BillType = "出库";
                        else
                            putPickQuestDto.BillType = "拣选出库";
                        putPickQuestDto.PalletBarcode = dto.PalletBarcode;
                        putPickQuestDto.LocationCode = dto.LocationCode;
                        putPickQuestDto.BatchNo = dto.BatchNo;
                        putPickQuestDto.Qty = dto.Qty;
                        putPickQuestDto.MaterialCode = dto.MaterialCode;
                        putPickQuestDtoslist.Add(putPickQuestDto);
                    }
                }
                string liststring = JsonConvert.SerializeObject(putPickQuestDtoslist);
                wsManager.SendMsgToAllClients(liststring);//给全部连上的客户端发
                return Ok(BaseResult.Result(result, "操作成功！", "200"));
            }
            return Ok(BaseResult.Result(result, "操作失败！" + message, "500"));
        }
        /// <summary>
        /// wcs扫到条码获取任务信息
        /// </summary>
        /// <param name="palletCode">托盘条码</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTaskByPallet(string palletCode)
        {
            if (string.IsNullOrEmpty(palletCode))
            {
                return Ok(BaseResult.Result("500", "参数有误！"));
            }
            //出库正常流程不在此处请求 但是为了测试
            var wcsTaskApiReq = new WcsTaskApiReq();
            var putwayOrderObj = putawayOrderRepository.QueryEntityWhere(s=>s.PalletBarcode == palletCode && s.Status == 4 && s.SourceType==1);
            var pickingOrderObj = pickingOrderRepository.QueryEntityWhere(s=>s.PalletBarcode == palletCode && s.Status == 4 && s.SourceType==2);
            //判断任务信息
            if (putwayOrderObj is not null)
            {
                wcsTaskApiReq.TaskCode = putwayOrderObj.Code;
                wcsTaskApiReq.CellCode = putwayOrderObj.LocationCode;
                wcsTaskApiReq.PalletCode = putwayOrderObj.PalletBarcode;
            }
            else if(pickingOrderObj is not null)
            {
                wcsTaskApiReq.TaskCode = pickingOrderObj.Code;
                wcsTaskApiReq.CellCode = pickingOrderObj.LocationCode;
                wcsTaskApiReq.PalletCode = pickingOrderObj.PalletBarcode;
            }
            else
            {
                return Ok(BaseResult.Result(wcsTaskApiReq, "WMS中没有此任务！", "500"));
            }
            
            var cellObj = cellService.GetCellByCode(wcsTaskApiReq.CellCode);//找出需要进行任务的仓位
            if (cellObj is null)
            {
                return Ok(BaseResult.Result(wcsTaskApiReq, $"WMS基础数据有误,没有任务中的此仓位{wcsTaskApiReq.CellCode}", "500"));
            }
            wcsTaskApiReq.CellCode = cellObj.Erpcode;//赋值给我Wcs ErpCode
            wcsTaskApiReq.Layer = cellObj.LayerNo;
            return Ok(BaseResult.Result(wcsTaskApiReq, "操作成功！", "200"));
        }
      
        /// <summary>
        /// 根据任务号查找是分拣还是直出
        /// </summary>
        /// <param name="palletCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetBillType(string taskCode)
        {
            if (string.IsNullOrEmpty(taskCode))
            {
                return Ok(BaseResult.Result("500", "参数为空！"));
            }
            var pickingOrderObj = pickingOrderRepository.QueryEntityWhere(s => s.Code == taskCode);
            if (pickingOrderObj == null)
            {
                return Ok(BaseResult.Result("500", "WMS中没有此出库任务！"));

            }
            return Ok(BaseResult.Result(pickingOrderObj.BillType,"成功" , "200"));
        }
        /// <summary>
        /// 根据托盘条码获取对应的erpCode
        /// </summary>
        /// <returns></returns>
        [HttpPost,Obsolete]
        public IActionResult GetErpCodeByPallet(string[] palletCodes)
        {
            try
            {
                if (palletCodes.Length == 0)
                {
                    return Ok(BaseResult.Result("500", "参数为空！"));
                }
                var cellByPallet = palletRepository.GetEntityWhereAll(s => palletCodes.Contains(s.PalletBarcode)).Select(s => s.LocationCode);
                var result = cellService.GetErpCodeByCodeList(cellByPallet.ToArray());
                return Ok(BaseResult.Result(result, "成功", "200"));
            }
            catch (Exception ex)
            {
                return Ok(BaseResult.Result(null, "失败", "500"));
            }
        }
        /// <summary>
        /// 测试 调用wcs接口切换为入库模式
        /// </summary>
        /// <returns></returns>
        [HttpGet,Obsolete]
        public IActionResult ModeSwitchApiTest()
        {
            try
            {
                return Ok(wcsHttp.ModeSwitchInApi());
            }
            catch (Exception ex)
            {
                return Ok(ex.Message);
            }
        }
        [HttpGet]
        public IActionResult WsTest(string msg)
        {
            var putlist = putawayOrderRepository.GetEntityWhereAll(x=>x.Status==4);
            List<PutPickQuestDto> putPickQuestDtoslist = new List<PutPickQuestDto>();
            if(putlist.Any())
            {
                foreach(var dto in putlist)
                {
                    PutPickQuestDto putPickQuestDto = new PutPickQuestDto();
                    putPickQuestDto.Code = dto.Code;
                    if (dto.BillType == 1)
                        putPickQuestDto.BillType = "入库";
                    else
                        putPickQuestDto.BillType = "拣选入库";
                    if (dto.SourceType == 3)
                        putPickQuestDto.BillType = "移库";
                    putPickQuestDto.PalletBarcode= dto.PalletBarcode;
                    putPickQuestDto.LocationCode = dto.LocationCode;
                    putPickQuestDto.BatchNo = dto.BatchNo;
                    putPickQuestDto.Qty = dto.Qty;
                    putPickQuestDto.MaterialCode = dto.MaterialCode;
                    putPickQuestDtoslist.Add(putPickQuestDto);
                }
            }
            var picklist = pickingOrderRepository.GetEntityWhereAll(x => x.Status == 4);
            if (picklist.Any())
            {
                foreach (var dto in picklist)
                {
                    PutPickQuestDto putPickQuestDto = new PutPickQuestDto();
                    putPickQuestDto.Code = dto.Code;
                    if (dto.BillType == 1)
                        putPickQuestDto.BillType = "出库";
                    else
                        putPickQuestDto.BillType = "拣选出库";
                    putPickQuestDto.PalletBarcode = dto.PalletBarcode;
                    putPickQuestDto.LocationCode = dto.LocationCode;
                    putPickQuestDto.BatchNo = dto.BatchNo;
                    putPickQuestDto.Qty = dto.Qty;
                    putPickQuestDto.MaterialCode = dto.MaterialCode;
                    putPickQuestDtoslist.Add(putPickQuestDto);
                }
            }
            string liststring = JsonConvert.SerializeObject(putPickQuestDtoslist);
            wsManager.SendMsgToAllClients(liststring);//给全部连上的客户端发
            //var apires = new ApiResult()
            //{
            //    data = new[] { 1, 12 },
            //    code = "200",
            //    count = 0,
            //    message = "OK",
            //};
            return Ok();
        }
        /// <summary>
        /// 更新托盘
        /// </summary>
        /// <returns></returns>
        //[HttpGet, Obsolete]
        //public IActionResult MultiAddPod()
        //{
        //    try
        //    {
        //        var palletList = palletRepository.GetAllEntityList().Select(s => new WcsPodInfo()
        //        {
        //            PodID = s.PalletBarcode,
        //            StoreID = cellService.GetErpCodeByCode(s.LocationCode),
        //            PositionType = string.IsNullOrEmpty(s.LocationCode) ? 99 : 0
        //        });
        //        var wcsApiRes = httpClient.Post<WcsApiRes>(Config.WcsMultiAddPodUrl, palletList);
        //        if (wcsApiRes.Code != 0)
        //        {
        //            return Ok(BaseResult.Result(false, wcsApiRes.Msg, "500"));
        //        }
        //        else return Ok(BaseResult.Result(true, wcsApiRes.Msg, "200"));
        //    }
        //    catch (Exception ex)
        //    {
        //        return Ok(BaseResult.Result(false, ex.Message, "500"));
        //    }
        //}
    }
}
